package com.lixh.sdk.base

import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import androidx.fragment.app.Fragment
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.lixh.sdk.base.event.EventRegister
import com.lixh.sdk.base.event.EventSend.obs
import com.lixh.sdk.base.util.log
import com.lixh.sdk.base.util.serialNo
import java.util.Stack
import kotlin.system.exitProcess


interface BaseAnalyticsDelegate {
    fun register(lifecycle: LifecycleOwner)
    fun registerEvent(lifecycle: LifecycleOwner, event: EventRegister)
    fun traceEvent(msg: String)

    fun appExit(isBackground: Boolean)
}

private var activityStack: Stack<Activity> = Stack()

class BaseAnalyticsDelegateImpl : BaseAnalyticsDelegate, DefaultLifecycleObserver {


    override fun register(lifecycle: LifecycleOwner) {
        when (lifecycle) {
            is Activity -> {
                activityStack.add(lifecycle)
                lifecycle.lifecycle.addObserver(this)
            }

            is Fragment -> {
                lifecycle.lifecycle.addObserver(this)
            }
        }
    }

    override fun registerEvent(lifecycle: LifecycleOwner, event: EventRegister) {
        obs[lifecycle] = mapOf(event.name to event)
    }

    override fun onStart(owner: LifecycleOwner) {

        traceEvent("Activity started")

    }


    override fun onStop(owner: LifecycleOwner) {
        traceEvent("Activity stopped")

    }

    override fun onDestroy(owner: LifecycleOwner) {
        super.onDestroy(owner)
        obs.remove(owner)
        if (owner is Activity) {
            activityStack.remove(owner)
            owner.lifecycle.removeObserver(this)
            owner.finish()
        }
    }

    /**
     * 结束所有Activity
     */
    private fun finishAllActivity() {
        activityStack.forEach { activity ->
            activity.finish()
        }
        activityStack.clear()
    }

    override fun appExit(isBackground: Boolean) {
        try {
            finishAllActivity()
            val manager =
                BaseApplication.appContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            manager.killBackgroundProcesses(
                BaseApplication.appContext
                    .packageName
            )

        } finally {
            // 注意，如果您有后台程序运行，请不要支持此句子
            if (!isBackground) {
                exitProcess(0)
            }
        }
    }

    override fun traceEvent(msg: String) {
        "traceEvent:$msg,time:${System.currentTimeMillis()},device:$serialNo".log()
    }
}